<?php
class Openfire  {
	private static $typeAdd = "add";
	private static $typeDelete = "delete";
	private static $typeUpdate = "update";

	private static $resultOk= "result";
	private static $resultError = "error";
	
	private $errorString;

	function addUserToOpenfire($username, $password){
		$params = $this->getBaseParams(Openfire::$typeAdd);
		$params["username"] = $username;
		$params["password"] = $password;
		$result = call_rest_service_sync($this->getUserServiceURL(), $params);
		return $this->success($result);
	}

	function deleteUserFromOpenfire($username){
		$params = $this->getBaseParams(Openfire::$typeDelete);
		$params["username"] = $username;
		$result = call_rest_service_sync($this->getUserServiceURL(), $params);
		return $this->success($result);
	}

	function updateUserFromOpenfire($username, $password){
		$params = $this->getBaseParams(Openfire::$typeUpdate);
		$params["username"] = $username;
		$params["password"] = $password;
		$result = call_rest_service_sync($this->getUserServiceURL(), $params);
		return $this->success($result);
	}

	private function getUserServiceURL(){
		return OPENFIRE_ROOT . OPENFIRE_USER_SERVICE;
	}

	private function getBaseParams($type){
		return array(
			"type" => $type,
			"secret" => OPENFIRE_USER_SECRET
		);
	}

	private function success($result){
		if($result) {
			$domElement = simplexml_load_string($result);
			$name = $domElement->getName();
			if ($name  == Openfire::$resultOk){
				return true;
			} else {
				$this->errorString = (string)$domElement;
				return false;
			}
		} else {
			$this->errorString = "IllegalArgumentException";
			return false;
		}
	}

	function getErrorString(){
		$errorMap = array(
			"IllegalArgumentException" => "Invalid parameters in openfire.",
			"UserNotFoundException	" => "User not found in openfire.",
			"RequestNotAuthorised" => "Bad secret key for openfire.",
			"UserAlreadyExistsException" => "User already exists in openfire.",
			"UserServiceDisabled" => "User service disabled in openfire.",
			"SharedGroupException" => "Shared group error in openfire."
		);
		return $errorMap[$this->errorString];
	}
	
	static function addMockUSers(){
		$open = new Openfire();
		$open->addUserToOpenfire("fixed1", "123456");
		$open->addUserToOpenfire("fixed2", "123456");
		$open->addUserToOpenfire("fixed3", "123456");
	}
};
